package com.hg.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hg.common.HttpStatus;
import com.hg.common.R;
import com.hg.pojo.HgMallDish;
import com.hg.pojo.HgMallShop;
import com.hg.pojo.dto.HgMallDishDTO;
import com.hg.service.HgMallDishService;
import com.hg.service.HgMallShopService;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2022-11-02
 */

@RestController
@CrossOrigin
public class HgMallDishController {

    @Autowired
    private HgMallDishService hgMallDishService;

    @Autowired
    private HgMallShopService hgMallShopService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 又来提升状态了 为我的菜品导出准备数据
     */
    private static List<HgMallDish> list;

    /**
     * 分页查询--------
     * @param currentPage
     * @param pageSize
     * @param dishName
     * @param shopName
     * @param category
     * @return
     */
    @GetMapping("/dishList")
    public R<Page<HgMallDishDTO>> getList(int currentPage, int pageSize, String dishName, String shopName, String category) {
        Page<HgMallDishDTO> hgMallDishDTOPage = null;
        String key = "admin";
        redisTemplate.delete(key);
        hgMallDishDTOPage = (Page<HgMallDishDTO>) redisTemplate.opsForValue().get(key);
        if (hgMallDishDTOPage != null){
            return R.success(HttpStatus.DISH_SUCCESS, "" ,hgMallDishDTOPage);
        }
        hgMallDishDTOPage = hgMallDishService.dishPage(currentPage, pageSize, dishName, shopName, category);
        redisTemplate.opsForValue().set(key,hgMallDishDTOPage,60, TimeUnit.MINUTES);
        return R.success(HttpStatus.DISH_SUCCESS, "" ,hgMallDishDTOPage);
    }

    /**
     *
     * @param hgMallDish
     * @return
     */
    @PutMapping("/updateDish")
    public R updateShop(@RequestBody HgMallDish hgMallDish) {
        Boolean aBoolean = hgMallDishService.updateDish(hgMallDish);
        if (aBoolean){
            redisTemplate.delete("admin");
            return R.success(HttpStatus.DISH_SUCCESS,"更新成功");
        }
        return R.error(HttpStatus.DISH_ERROR,"更新失败");
    }

    /**
     * 修改是否上下架
     * @param id
     * @param status
     * @return
     */
    @PutMapping("/updateDishStatus/{id}/{status}")
    public R<String> updateStatus(@PathVariable Long id,@PathVariable int status) {

        if (id!=null){
            LambdaUpdateWrapper<HgMallDish> lm = new LambdaUpdateWrapper<>();
            lm.set(HgMallDish::getStatus, status);
            lm.eq(HgMallDish::getId, id);
            hgMallDishService.update(lm);
            redisTemplate.delete("admin");
            return R.success(HttpStatus.DISH_SUCCESS,"更新成功");
        }
        return R.error(HttpStatus.DISH_ERROR,"传入的id为空");
    }

    /**
     * 删除菜品
     * @param id
     * @return
     */
    @DeleteMapping("/dishDelete/{id}")
    @Transactional
    public R<String> deleteShop(@PathVariable Long id) {

        Boolean aBoolean = hgMallDishService.deleteDishById(id);
        if (aBoolean) {
            redisTemplate.delete("admin");
            return R.success(HttpStatus.DELETE_SUCCESS, "删除成功");
        } else {
            return R.error(HttpStatus.DELETE_ERROR,"删除失败");
        }

    }

    /**
     * 批量删除餐品
     * @param ids
     * @return
     */
    @PostMapping("/deleteDishIds/{ids}")
    public R<String> deleteShopIds(@PathVariable Long[] ids) {
        Boolean aBoolean = hgMallDishService.deleteShopByIds(ids);
        if (aBoolean){
            redisTemplate.delete("admin");
            return R.success(HttpStatus.DISH_SUCCESS,"删除成功");
        }
        return R.error(HttpStatus.DISH_ERROR,"删除失败");
    }


    @PostMapping("/mySelectMyDish")
    public R<List<HgMallDish>> selectShopOne(@RequestBody Map<String,String> map){

        String shopId = map.get("shopId");
        String key = "myDish" + shopId;
        String dishName = map.get("dishName");
        String category = map.get("category");

        redisTemplate.delete(key);
        list = (List<HgMallDish>) redisTemplate.opsForValue().get(key);
        if (list != null){
            return R.success(HttpStatus.DISH_SUCCESS,list);
        }
        //先通过当前登入用户关联的店铺id查询出本用户所有的菜品
        LambdaQueryWrapper<HgMallDish> lm =new LambdaQueryWrapper<>();
        lm.select(
                HgMallDish::getId,
                HgMallDish::getName,
                HgMallDish::getIntroduce,
                HgMallDish::getType,
                HgMallDish::getPrice,
                HgMallDish::getStatus,
                HgMallDish::getDelFlag,
                HgMallDish::getImg);
        lm.eq(HgMallDish::getShopId,shopId);
        lm.eq(HgMallDish::getDelFlag,0);
        lm.like(dishName != null,HgMallDish::getName,dishName);
        lm.like(category != null,HgMallDish::getType,category);
        list = hgMallDishService.list(lm);
        if (list!=null){
            redisTemplate.opsForValue().set(key,list,60,TimeUnit.MINUTES);
            return R.success(HttpStatus.DISH_SUCCESS,list);
        }
        return R.error(HttpStatus.DISH_ERROR,"管理员还想有菜吃？");
    }


    /**
     * 导出接口
     */
    @GetMapping("/dishExport")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        LambdaQueryWrapper<HgMallDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.select(
                HgMallDish::getId,
                HgMallDish::getName,
                HgMallDish::getIntroduce,
                HgMallDish::getPrice,
                HgMallDish::getType,
                HgMallDish::getStatus,
                HgMallDish::getShopId,
                HgMallDish::getSales);
        List<HgMallDish> list = hgMallDishService.list(dishLambdaQueryWrapper);
        List<HgMallDishDTO> dishDTOS = list.stream().map((item) -> {
            HgMallDishDTO hgMallDishDTO = new HgMallDishDTO();
            //对象拷贝
            BeanUtils.copyProperties(item,hgMallDishDTO);
            //获取商家id再查询它的名字
            Integer shopId = item.getShopId();
            //条件构造器
            LambdaQueryWrapper<HgMallShop> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(HgMallShop::getId,shopId);
            queryWrapper.select(HgMallShop::getName);
            //执行查询获取商家名字
            String name = hgMallShopService.getOne(queryWrapper).getName();
            hgMallDishDTO.setShopName(name);
            return hgMallDishDTO;
        }).collect(Collectors.toList());
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "菜品ID");
        writer.addHeaderAlias("name", "菜品名称");
        writer.addHeaderAlias("introduce", "菜品介绍");
        writer.addHeaderAlias("price", "价格(元)");
        writer.addHeaderAlias("sales", "销量");
        writer.addHeaderAlias("shopName", "商家");
        writer.addHeaderAlias("type", "菜品类型");
        writer.addHeaderAlias("status", "是否下架");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(dishDTOS, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("菜品信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }



    /**
     * 导出接口
     */
    @GetMapping("/MydishExport")
    public void Myexport(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据

        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "菜品ID");
        writer.addHeaderAlias("name", "菜品名称");
        writer.addHeaderAlias("introduce", "菜品介绍");
        writer.addHeaderAlias("price", "价格(元)");
        writer.addHeaderAlias("sales", "销量");
        writer.addHeaderAlias("shopName", "商家");
        writer.addHeaderAlias("type", "菜品类型");
        writer.addHeaderAlias("status", "是否下架");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("菜品信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }


    /**
     * 订单信息中通过shopID获取菜品
     *
     * @param shopId 商店id
     * @return {@link R}<{@link List}<{@link HgMallDish}>>
     */
    @GetMapping("/getDishOptions/{shopId}")
    public R<List<HgMallDish>> getDishOptions(@PathVariable Integer shopId){
        List<HgMallDish> list= hgMallDishService.getDishOptionsByShopId(shopId);
        if (list!=null){
            return R.success(HttpStatus.DISH_SUCCESS,list);
        }
        return R.error(HttpStatus.DISH_ERROR,"当前店铺没有菜品");
    }
}
